package com.ysf.lib_excel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

public class ExcelWriter {

    private static final LinkedList<XmlBean> xmlListData = new LinkedList<>();

    public static void main(String[] args) {
        //读取翻译文件
        parseOriginXml();
        try {
            generateExcel();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void generateExcel() throws IOException {
        // 创建一个新的工作簿
        final Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表(sheet)
        final Sheet sheet = workbook.createSheet("sheet0");
        int index = 0;
        for (XmlBean bean : xmlListData) {
            // 创建行（0基索引）
            final Row row = sheet.createRow(index);
            // 创建单元格并设置值
            final Cell cell = row.createCell(0);
            cell.setCellValue(bean.valueStr);
            index++;
        }
        final String excelFilePath = "D:\\strings/no_trans.xlsx";
        // 写入到文件
        try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
            try {
                workbook.write(outputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // 关闭工作簿释放资源
        try {
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解析原始xml文件
     */
    private static void parseOriginXml() {
        final String xmlFilePath = "D:\\strings/test_string.xml";
        Document document;
        try {
            SAXReader saxReader = new SAXReader();
            document = saxReader.read(new File(xmlFilePath));
            final Element rootElement = document.getRootElement();
            XmlBean bean;
            for (Iterator<Element> i = rootElement.elementIterator(); i.hasNext(); ) {
                Element element = i.next();
                bean = new XmlBean();
                bean.key = element.attributeValue("name");
                bean.valueStr = element.getText();
                xmlListData.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
